package com.imonsoft.sqm.service.business.supplier_quality;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import com.google.gson.reflect.TypeToken;
import com.imonsoft.common.constant.ConstantDict;
import com.imonsoft.common.constant.ConstantSqm;
import com.imonsoft.common.exception.SystemException;
import com.imonsoft.common.httpModel.DataGrid;
import com.imonsoft.common.httpModel.Pager;
import com.imonsoft.common.httpModel.ReturnMessage;
import com.imonsoft.common.util.JsonUtil;
import com.imonsoft.common.util.StringUtil;
import com.imonsoft.sqm.dao.business.supplier_quality.AnswerProblemDAO;
import com.imonsoft.sqm.pojo.basedata.Dictionary;
import com.imonsoft.sqm.pojo.basedata.Supplier;
import com.imonsoft.sqm.pojo.business.supplier_quality.AnswerProblem;
import com.imonsoft.sqm.pojo.business.supplier_quality.AnswerProblemExample;
import com.imonsoft.sqm.service.basedata.DictionaryService;
import com.imonsoft.sqm.service.basedata.SupplierService;
import com.imonsoft.sqm.validator.business.supplier_quality.AnswerProblemValidator;
import com.imonsoft.sqm.vo.business.supplier_quality.AnswerProblemVo;
import com.imonsoft.sqm.web.excel.AnswerProblemExcel.AnswerProblemImportDto;

@Service("answerProblemService")
public class AnswerProblemServiceImpl implements AnswerProblemService {

	@Autowired
	private AnswerProblemDAO answerProblemDAO;

	@Autowired
	private SupplierService supplierService;

	@Autowired
	private AnswerProblemValidator answerProblemValidator;

	@Autowired
	private DictionaryService dictionaryService;

	@Override
	public DataGrid<AnswerProblemVo> getDataGridVoBy(
			AnswerProblem answerProblem, Pager pager) {

		return answerProblemDAO.getDataGridVoBy(answerProblem, pager);
	}

	@Override
	public void txAddAnswerProblem(String answer, String answerDetail,
			ReturnMessage message, BindingResult result) throws Exception {

		List<AnswerProblem> answerProblemList = new ArrayList<AnswerProblem>();

		AnswerProblem vo = new AnswerProblem();
		List<Map<String, String>> list = null;
		Map<String, String> map = null;
		if (StringUtil.isNotBlank(answer)) {
			map = JsonUtil.json2Bean(answer,
					new TypeToken<Map<String, String>>() {
					});
		}
		if (StringUtil.isNotBlank(answerDetail)) {
			// 把json字符串转换成对象
			list = JsonUtil.json2Bean(answerDetail,
					new TypeToken<List<Map<String, String>>>() {
					});
		}
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, String> detailMap = list.get(i);
				AnswerProblem bean = new AnswerProblem();
				BeanUtils.populate(bean, detailMap);
				answerProblemList.add(bean);
			}
		}
		BeanUtils.populate(vo, map);
		Supplier supplier = supplierService
				.get(Long.valueOf(vo.getSupplierId()));
		vo.setSupplierCode(supplier.getCode());
		vo.setSupplierName(supplier.getName());
		answerProblemValidator.methodAddValidate(vo, result);
		if (result.hasErrors()) {
			message.setObj(answerProblemValidator.getErrors(result));
		} else {

			List<AnswerProblem> lists = findListByStateDelete(vo);
			for (AnswerProblem answerProblem : lists) {
				answerProblem.setState(ConstantSqm.STATUS_NORMAL);
				answerProblem.setComment(null);
				answerProblem.setType(null);
				answerProblem.setValue(null);
				answerProblemDAO.updateAnswerProblemByPrimaryKey(answerProblem);
			}
			List<Dictionary> d1 = dictionaryService
					.findDictionaryByType(ConstantDict.AnswerProblem_ANSER);
			for (AnswerProblem answerProblem : answerProblemList) {

				for (Dictionary dictionary : d1) {
					if (dictionary.getName().equals(answerProblem.getType())) {
						answerProblem.setType(dictionary.getCode());
					}
				}

				answerProblem.setSupplierId(vo.getSupplierId());
				answerProblem.setSupplierCode(vo.getSupplierCode());
				answerProblem.setSupplierName(vo.getSupplierName());
				answerProblem.setYear(vo.getYear());
				List<AnswerProblem> obj = findListByState(answerProblem);
				if (obj != null && obj.size() > 0) {
					AnswerProblem bean = obj.get(0);
					bean.setComment(answerProblem.getComment());
					bean.setType(answerProblem.getType());
					bean.setValue(answerProblem.getValue());
					if (!StringUtil.isBlank(bean.getType())
							|| bean.getValue() != null
							|| !StringUtil.isBlank(bean.getComment())) {
						answerProblemDAO.updateAnswerProblemByPrimaryKey(bean);
					}
				} else {
					answerProblem.setState(ConstantSqm.STATUS_NORMAL);
					if (!StringUtil.isBlank(answerProblem.getType())
							|| answerProblem.getValue() != null
							|| !StringUtil.isBlank(answerProblem.getComment())) {
						answerProblemDAO.insertAnswerProblem(answerProblem);
					}
				}
			}
			message.setSuccess(true);
			message.setMsg(ConstantSqm.OPERATE_SUCCESS);
		}
	}

	@Override
	public int delete(Long id) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public List<AnswerProblem> findList(AnswerProblem entity) {
		AnswerProblemExample example = new AnswerProblemExample();
		AnswerProblemExample.Criteria criteria = example.createCriteria();
		criteria.andStateNotEqualTo(ConstantSqm.STATUS_DELETE);
		criteria.andSupplierIdEqualTo(entity.getSupplierId());
		criteria.andYearEqualTo(entity.getYear());
		return answerProblemDAO.selectAnswerProblemByExample(example);
	}

	@Override
	public AnswerProblem get(Long id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public DataGrid<AnswerProblem> getDataGrid(AnswerProblem entity, Pager pager) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Long insert(AnswerProblem entity) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int update(AnswerProblem entity) {
		// TODO Auto-generated method stub
		return 0;
	}

	public List<AnswerProblem> findListByStateDelete(AnswerProblem entity) {
		AnswerProblemExample example = new AnswerProblemExample();
		AnswerProblemExample.Criteria criteria = example.createCriteria();
		criteria.andStateEqualTo(ConstantSqm.STATUS_DELETE);
		criteria.andSupplierIdEqualTo(entity.getSupplierId());
		criteria.andYearEqualTo(entity.getYear());
		return answerProblemDAO.selectAnswerProblemByExample(example);
	}

	public List<AnswerProblem> findListByState(AnswerProblem entity) {
		AnswerProblemExample example = new AnswerProblemExample();
		AnswerProblemExample.Criteria criteria = example.createCriteria();
		criteria.andStateEqualTo(ConstantSqm.STATUS_NORMAL);
		criteria.andSupplierIdEqualTo(entity.getSupplierId());
		criteria.andYearEqualTo(entity.getYear());
		criteria.andMonthEqualTo(entity.getMonth());
		return answerProblemDAO.selectAnswerProblemByExample(example);
	}

	@Override
	public void deleteAnswerProblem(String answerDetail) throws Exception {

		List<AnswerProblem> answerProblem = new ArrayList<AnswerProblem>();
		List<Map<String, String>> list = null;
		if (StringUtil.isNotBlank(answerDetail)) {
			// 把json字符串转换成对象
			list = JsonUtil.json2Bean(answerDetail,
					new TypeToken<List<Map<String, String>>>() {
					});
		}
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, String> detailMap = list.get(i);
				AnswerProblem bean = new AnswerProblem();
				BeanUtils.populate(bean, detailMap);
				answerProblem.add(bean);
			}
		}
		if (answerProblem.size() != 0) {
			for (AnswerProblem bean : answerProblem) {

				AnswerProblemExample example = new AnswerProblemExample();
				AnswerProblemExample.Criteria criteria = example
						.createCriteria();
				criteria.andStateNotEqualTo(ConstantSqm.STATUS_DELETE);
				criteria.andYearEqualTo(bean.getYear());
				criteria.andSupplierIdEqualTo(bean.getSupplierId());

				List<AnswerProblem> dataList = answerProblemDAO
						.selectAnswerProblemByExample(example);

				if (dataList != null && dataList.size() != 0) {
					for (AnswerProblem data : dataList) {
						data.setState(ConstantSqm.STATUS_DELETE);
						answerProblemDAO.updateAnswerProblemByPrimaryKey(data);
					}
				}

			}
		}

	}

	@Override
	public AnswerProblemVo getModifyData(Long supplierId, String year) {
		AnswerProblemVo vo = new AnswerProblemVo();
		vo.setSupplierId(StringUtil.fixup(supplierId));
		Supplier supplier = supplierService.get(supplierId);
		vo.setSupplierCode(supplier.getCode());
		vo.setSupplierName(supplier.getName());
		vo.setYear(year);
		List<Dictionary> d1 = dictionaryService
				.findDictionaryByType(ConstantDict.AnswerProblem_ANSER);
		for (int i = 1; i <= 12; i++) {
			AnswerProblem bean = null;
			AnswerProblemExample example = new AnswerProblemExample();
			AnswerProblemExample.Criteria criteria = example.createCriteria();
			criteria.andStateNotEqualTo(ConstantSqm.STATUS_DELETE);
			criteria.andSupplierIdEqualTo(Integer.parseInt(StringUtil
					.fixup(supplier.getId())));
			criteria.andYearEqualTo(year);
			criteria.andMonthEqualTo(StringUtil.paddingZero(String.valueOf(i),2));
			List<AnswerProblem> list = answerProblemDAO
					.selectAnswerProblemByExample(example);
			if (list.size() != 0) {
				bean = list.get(0);
				if (i == 1) {
					vo.setJanuary(StringUtil.fixup(bean.getValue()));
					vo.setJanuaryComment(StringUtil.fixup(bean.getComment()));
					vo.setJanuaryType(StringUtil.fixup(bean.getType()));
					if (!StringUtil.isBlank(vo.getJanuaryType())) {
						for (Dictionary dictionary : d1) {
							if (dictionary.getCode()
									.equals(vo.getJanuaryType())) {
								vo.setJanuaryType(dictionary.getName());
							}
						}
					}
				} else if (i == 2) {
					vo.setFebruary(StringUtil.fixup(bean.getValue()));
					vo.setFebruaryComment(StringUtil.fixup(bean.getComment()));
					vo.setFebruaryType(StringUtil.fixup(bean.getType()));

					if (!StringUtil.isBlank(vo.getFebruaryType())) {
						for (Dictionary dictionary : d1) {
							if (dictionary.getCode().equals(
									vo.getFebruaryType())) {
								vo.setFebruaryType(dictionary.getName());
							}
						}
					}

				} else if (i == 3) {
					vo.setMarch(StringUtil.fixup(bean.getValue()));
					vo.setMarchComment(StringUtil.fixup(bean.getComment()));
					vo.setMarchType(StringUtil.fixup(bean.getType()));

					if (!StringUtil.isBlank(vo.getMarchType())) {
						for (Dictionary dictionary : d1) {
							if (dictionary.getCode().equals(vo.getMarchType())) {
								vo.setMarchType(dictionary.getName());
							}
						}
					}

				} else if (i == 4) {
					vo.setApril(StringUtil.fixup(bean.getValue()));
					vo.setAprilComment(StringUtil.fixup(bean.getComment()));
					vo.setAprilType(StringUtil.fixup(bean.getType()));

					if (!StringUtil.isBlank(vo.getAprilType())) {
						for (Dictionary dictionary : d1) {
							if (dictionary.getCode().equals(vo.getAprilType())) {
								vo.setAprilType(dictionary.getName());
							}
						}
					}

				} else if (i == 5) {
					vo.setMay(StringUtil.fixup(bean.getValue()));
					vo.setMayComment(StringUtil.fixup(bean.getComment()));
					vo.setMayType(StringUtil.fixup(bean.getType()));

					if (!StringUtil.isBlank(vo.getMayType())) {
						for (Dictionary dictionary : d1) {
							if (dictionary.getCode().equals(vo.getMayType())) {
								vo.setMayType(dictionary.getName());
							}
						}
					}

				} else if (i == 6) {
					vo.setJune(StringUtil.fixup(bean.getValue()));
					vo.setJuneComment(StringUtil.fixup(bean.getComment()));
					vo.setJuneType(StringUtil.fixup(bean.getType()));

					if (!StringUtil.isBlank(vo.getJuneType())) {
						for (Dictionary dictionary : d1) {
							if (dictionary.getCode().equals(vo.getJuneType())) {
								vo.setJuneType(dictionary.getName());
							}
						}
					}

				} else if (i == 7) {
					vo.setJuly(StringUtil.fixup(bean.getValue()));
					vo.setJulyComment(StringUtil.fixup(bean.getComment()));
					vo.setJulyType(StringUtil.fixup(bean.getType()));

					if (!StringUtil.isBlank(vo.getJulyType())) {
						for (Dictionary dictionary : d1) {
							if (dictionary.getCode().equals(vo.getJulyType())) {
								vo.setJulyType(dictionary.getName());
							}
						}
					}
				} else if (i == 8) {
					vo.setAugust(StringUtil.fixup(bean.getValue()));
					vo.setAugustComment(StringUtil.fixup(bean.getComment()));
					vo.setAugustType(StringUtil.fixup(bean.getType()));

					if (!StringUtil.isBlank(vo.getAugustType())) {
						for (Dictionary dictionary : d1) {
							if (dictionary.getCode().equals(vo.getAugustType())) {
								vo.setAugustType(dictionary.getName());
							}
						}
					}

				} else if (i == 9) {
					vo.setSeptember(StringUtil.fixup(bean.getValue()));
					vo.setSeptemberComment(StringUtil.fixup(bean.getComment()));
					vo.setSeptemberType(StringUtil.fixup(bean.getType()));

					if (!StringUtil.isBlank(vo.getSeptemberType())) {
						for (Dictionary dictionary : d1) {
							if (dictionary.getCode().equals(
									vo.getSeptemberType())) {
								vo.setSeptemberType(dictionary.getName());
							}
						}
					}
				} else if (i == 10) {
					vo.setOctober(StringUtil.fixup(bean.getValue()));
					vo.setOctoberComment(StringUtil.fixup(bean.getComment()));
					vo.setOctoberType(StringUtil.fixup(bean.getType()));

					if (!StringUtil.isBlank(vo.getOctoberType())) {
						for (Dictionary dictionary : d1) {
							if (dictionary.getCode()
									.equals(vo.getOctoberType())) {
								vo.setOctoberType(dictionary.getName());
							}
						}
					}
				} else if (i == 11) {
					vo.setNovember(StringUtil.fixup(bean.getValue()));
					vo.setNovemberComment(StringUtil.fixup(bean.getComment()));
					vo.setNovemberType(StringUtil.fixup(bean.getType()));

					if (!StringUtil.isBlank(vo.getNovemberType())) {
						for (Dictionary dictionary : d1) {
							if (dictionary.getCode().equals(
									vo.getNovemberType())) {
								vo.setNovemberType(dictionary.getName());
							}
						}
					}
				} else if (i == 12) {
					vo.setDecember(StringUtil.fixup(bean.getValue()));
					vo.setDecemberComment(StringUtil.fixup(bean.getComment()));
					vo.setDecemberType(StringUtil.fixup(bean.getType()));

					if (!StringUtil.isBlank(vo.getDecemberType())) {
						for (Dictionary dictionary : d1) {
							if (dictionary.getCode().equals(
									vo.getDecemberType())) {
								vo.setDecemberType(dictionary.getName());
							}
						}
					}
				}
			}
		}

		return vo;
	}

	@Override
	public void txUpdateOrAddAnswer(String answerDetail, String answer)
			throws Exception {

		AnswerProblem answerProblem = null;
		Map<String, String> map = null;
		List<Map<String, String>> list = null;
		List<AnswerProblem> answerList = new ArrayList<AnswerProblem>();

		if (StringUtil.isNotBlank(answer)) {
			map = JsonUtil.json2Bean(answer,
					new TypeToken<Map<String, String>>() {
					});
		}
		if (StringUtil.isNotBlank(answerDetail)) {
			// 把json字符串转换成对象
			list = JsonUtil.json2Bean(answerDetail,
					new TypeToken<List<Map<String, String>>>() {
					});
		}

		if (map != null) {
			answerProblem = new AnswerProblem();
			BeanUtils.populate(answerProblem, map);
		}

		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, String> detailMap = list.get(i);
				AnswerProblem bean = new AnswerProblem();
				BeanUtils.populate(bean, detailMap);
				answerList.add(bean);
			}
		}

		List<Dictionary> d1 = dictionaryService
				.findDictionaryByType(ConstantDict.AnswerProblem_ANSER);
		Supplier supplier = supplierService.get(Long.valueOf(answerProblem
				.getSupplierId()));

		for (int i = 1; i <= 12; i++) {
			AnswerProblem bean = null;
			AnswerProblemExample example = new AnswerProblemExample();
			AnswerProblemExample.Criteria criteria = example.createCriteria();
			criteria.andStateNotEqualTo(ConstantSqm.STATUS_DELETE);
			criteria.andSupplierIdEqualTo(answerProblem.getSupplierId());
			criteria.andYearEqualTo(answerProblem.getYear());
			criteria.andMonthEqualTo(StringUtil.paddingZero(String.valueOf(i),2));
			List<AnswerProblem> answerProblemList = answerProblemDAO
					.selectAnswerProblemByExample(example);
			// 修改
			if (answerProblemList.size() != 0) {
				bean = answerProblemList.get(0);

				for (AnswerProblem answerProblem2 : answerList) {
					if (i == Integer.parseInt(answerProblem2.getMonth())) {
						bean.setComment(answerProblem2.getComment());
						bean.setValue(answerProblem2.getValue());
						if (!StringUtil.isBlank(answerProblem2.getType())) {
							for (Dictionary dictionary : d1) {
								if (dictionary.getName().equals(
										answerProblem2.getType())) {
									bean.setType(dictionary.getCode());
								}
							}
						}
						break;
					}
				}
				if (!StringUtil.isBlank(bean.getType())
						|| bean.getValue() != null
						|| !StringUtil.isBlank(bean.getComment())) {
					answerProblemDAO.updateAnswerProblemByPrimaryKey(bean);
				}
			} else {

				for (AnswerProblem answerProblem2 : answerList) {
					if (i == Integer.parseInt(answerProblem2.getMonth())) {
						// 新增
						AnswerProblem pojo = new AnswerProblem();
						pojo.setComment(answerProblem2.getComment());
						pojo.setValue(answerProblem2.getValue());
						pojo.setYear(answerProblem.getYear());
						pojo.setSupplierId(Integer.parseInt(supplier.getId()
								.toString()));
						pojo.setSupplierCode(supplier.getCode());
						pojo.setSupplierName(supplier.getName());
						pojo.setMonth(answerProblem2.getMonth());
						pojo.setState(ConstantSqm.STATUS_NORMAL);
						if (!StringUtil.isBlank(answerProblem2.getType())) {
							for (Dictionary dictionary : d1) {
								if (dictionary.getName().equals(
										answerProblem2.getType())) {
									pojo.setType(dictionary.getCode());
								}
							}
						}
						if (!StringUtil.isBlank(pojo.getType())
								|| pojo.getValue() != null
								|| !StringUtil.isBlank(pojo.getComment())) {
							answerProblemDAO.insertAnswerProblem(pojo);
						}
						break;
					}
				}

			}
		}

	}
	/**
	 * zhouwei 系统导入保存
	 * 
	 * @param entity
	 * @return
	 */
	@Override
	public void txInsertForSys(List<AnswerProblemImportDto> answerProblemImportDtoList){
		if (null == answerProblemImportDtoList) {
			throw new SystemException("提交数据不能为空");
		}
		for (AnswerProblemImportDto a:answerProblemImportDtoList) {
			if(StringUtil.isNotEmpty(a.getValueJanuary())&&StringUtil.isNotEmpty(a.getTypeJanuary())){
				txAddOrUpdateForSys(1, a, a.getTypeJanuary(), a.getValueJanuary());
			}
			if(StringUtil.isNotEmpty(a.getValueFebruary())&&StringUtil.isNotEmpty(a.getTypeFebruary())){
				txAddOrUpdateForSys(2, a, a.getTypeFebruary(), a.getValueFebruary());
			}
			if(StringUtil.isNotEmpty(a.getValueMarch())&&StringUtil.isNotEmpty(a.getTypeMarch())){
				txAddOrUpdateForSys(3, a, a.getTypeMarch(), a.getValueMarch());
			}
			if(StringUtil.isNotEmpty(a.getValueApril())&&StringUtil.isNotEmpty(a.getTypeApril())){
				txAddOrUpdateForSys(4, a, a.getTypeApril(), a.getValueApril());
			}
			if(StringUtil.isNotEmpty(a.getValueMay())&&StringUtil.isNotEmpty(a.getTypeMay())){
				txAddOrUpdateForSys(5, a, a.getTypeMay(), a.getValueMay());
			}
			if(StringUtil.isNotEmpty(a.getValueJune())&&StringUtil.isNotEmpty(a.getTypeJune())){
				txAddOrUpdateForSys(6, a, a.getTypeJune(), a.getValueJune());
			}
			if(StringUtil.isNotEmpty(a.getValueJuly())&&StringUtil.isNotEmpty(a.getTypeJuly())){
				txAddOrUpdateForSys(7, a, a.getTypeJuly(), a.getValueJuly());
			}
			if(StringUtil.isNotEmpty(a.getValueAugust())&&StringUtil.isNotEmpty(a.getTypeAugust())){
				txAddOrUpdateForSys(8, a, a.getTypeAugust(), a.getValueAugust());
			}
			if(StringUtil.isNotEmpty(a.getValueSeptember())&&StringUtil.isNotEmpty(a.getTypeSeptember())){
				txAddOrUpdateForSys(9, a, a.getTypeSeptember(), a.getValueSeptember());
			}
			if(StringUtil.isNotEmpty(a.getValueOctober())&&StringUtil.isNotEmpty(a.getTypeOctober())){
				txAddOrUpdateForSys(10, a, a.getTypeOctober(), a.getValueOctober());
			}
			if(StringUtil.isNotEmpty(a.getValueNovember())&&StringUtil.isNotEmpty(a.getTypeNovember())){
				txAddOrUpdateForSys(11, a, a.getTypeNovember(), a.getValueNovember());
			}
			if(StringUtil.isNotEmpty(a.getValueDecember())&&StringUtil.isNotEmpty(a.getTypeDecember())){
				txAddOrUpdateForSys(12, a, a.getTypeDecember(), a.getValueDecember());
			}
			
		}
	}
	/**
	 * 新增或者修改，系統导入
	 * @param month
	 * @param incomingImportDto
	 */
	public void txAddOrUpdateForSys(int month,AnswerProblemImportDto answerProblemImportDto,String Type,String value){
		AnswerProblem bean =new AnswerProblem();
		AnswerProblemExample example = new AnswerProblemExample();
		AnswerProblemExample.Criteria criteria = example.createCriteria();
		criteria.andStateNotEqualTo(ConstantSqm.STATUS_DELETE);
		criteria.andSupplierIdEqualTo(answerProblemImportDto.getSupplierId());
		criteria.andYearEqualTo(answerProblemImportDto.getYear());
		criteria.andMonthEqualTo(String.valueOf(month));
		List<AnswerProblem> answerProblemList = answerProblemDAO.selectAnswerProblemByExample(example);
		if(answerProblemList!=null&&answerProblemList.size()>0){
			//修改
			bean=answerProblemList.get(0);
			bean.setValue(Integer.parseInt(StringUtil.fixup(value)));
			bean.setType(Type);
			answerProblemDAO.updateAnswerProblemByPrimaryKey(bean);
		}else{
			org.springframework.beans.BeanUtils.copyProperties(answerProblemImportDto, bean);
			bean.setValue(Integer.parseInt(StringUtil.fixup(value)));
			bean.setType(Type);
			bean.setMonth(StringUtil.fixup(month));
			bean.setState(ConstantSqm.STATUS_NORMAL);
			answerProblemDAO.insertAnswerProblem(bean);
		}
	}

}
